package top.mcwebsite.playandroid.common.flex

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.unit.Dp
import kotlin.math.roundToInt


@Composable
fun SimpleFlexRow(
    space: Dp,
    modifier: Modifier = Modifier,
    content: @Composable () -> Unit,
) {
    Layout(
        modifier = modifier,
        content = content
    ) { measurables, constraints ->
        // Don't constrain child views further, measure them with given constraints
        // List of measured children
        var minHeight = 0
        val spacePx = space.toPx().roundToInt()
        var maxLineHeight = 0
        var width = 0
        val placeables = measurables.map { measurable ->
            // Measure each children
            val placeable = measurable.measure(constraints)
            if (width + spacePx + placeable.width > constraints.maxWidth) {
                width = placeable.width
                minHeight += maxLineHeight + spacePx
                maxLineHeight = placeable.height
            } else {
                maxLineHeight = maxOf(placeable.height, maxLineHeight)
                width += (if (width == 0) placeable.width else placeable.width + spacePx)
            }
            placeable
        }
        if (width != 0) {
            minHeight += maxLineHeight
        }
        maxLineHeight = 0
        width = 0
        // Set the size of the layout as big as it can
        layout(constraints.maxWidth, minHeight) {
            // Track the y co-ord we have placed children up to
            var index = 0
            var yPosition = 0
            while (index < placeables.size) {
                placeables[index].place(width, yPosition)
                width += spacePx + placeables[index].width
                maxLineHeight = maxOf(maxLineHeight, placeables[index].height)
                if (index + 1 < placeables.size && width + placeables[index + 1].width > constraints.maxWidth) {
                    yPosition += maxLineHeight + spacePx
                    width = 0
                    maxLineHeight = 0
                }
                index++
            }
        }

    }
}